<template>
  <div 
    v-if="visible" 
    class="ai-reply-alert" 
    :data-chat-id="chatId"
  >
    <div class="ai-reply-header">
      <h4>📋 提醒摘要 (对话: {{ nickname || chatId }})</h4>
      <button class="close-btn" @click="closeAlert">×</button>
    </div>
    <div class="ai-reply-content">
      <p v-if="structuredData && structuredData['提醒摘要']">{{ structuredData['提醒摘要']['内容'] }}</p>
      <div class="reply-input-container">
        <textarea 
          id="replyContent" 
          v-model="replyContent"
          placeholder="回复内容"
        ></textarea>
        <div class="reply-actions">
          <button class="send-btn" @click="sendReply">发送</button>
        </div>
      </div>
    </div>
    <div class="ai-reply-suggestions" v-if="showSuggestions && structuredData && structuredData['回复建议']">
      <h4>💡 回复建议列表</h4>
      <div class="suggestions-list">
        <div 
          v-for="(suggestion, index) in structuredData['回复建议']" 
          :key="index"
          class="suggestion-item"
        >
          <div class="suggestion-purpose">
            🎯 回复目的 {{ index + 1 }}：{{ suggestion['好处目的'] || '' }}
          </div>
          <div class="suggestion-content">
            <strong>📝 内容：</strong><br>
            {{ suggestion['内容'] || '' }}
          </div>
          <div class="suggestion-proof" v-if="suggestion['证明材料']">
            <strong>📎 证明材料：</strong><br>
            {{ suggestion['证明材料'] }}
          </div>
          <button class="use-suggestion-btn" @click="useSuggestion(suggestion['内容'])">使用此回复</button>
        </div>
      </div>
    </div>
    <div class="ai-reply-footer">
      <button class="view-btn" @click="toggleSuggestions">
        {{ showSuggestions ? '收起回复建议' : '查看回复建议' }}
      </button>
      <button class="close-btn" @click="closeAlert">关闭</button>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, watch, onMounted } from 'vue';
import { getAuthInfo } from '../utils/erpapi';
import { setEditorContent2 } from '../utils/domtools';

export default defineComponent({
  name: 'AiReplyAlert',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    structuredData: {
      type: Object,
      default: () => ({})
    },
    chatId: {
      type: String,
      default: ''
    },
    nickname: {
      type: String,
      default: ''
    }
  },
  emits: ['close'],
  setup(props, { emit }) {
    const showSuggestions = ref(false);
    const replyContent = ref('');

    // 初始化回复内容为第一个建议
    watch(() => props.structuredData, (newVal) => {
      if (newVal && newVal['回复建议'] && newVal['回复建议'].length > 0) {
        replyContent.value = newVal['回复建议'][0]['内容'] || '';
      } else if (newVal && newVal['提醒摘要']) {
        replyContent.value = newVal['提醒摘要']['内容'] || '';
      }
    }, { immediate: true });

    // 切换显示/隐藏建议列表
    const toggleSuggestions = () => {
      showSuggestions.value = !showSuggestions.value;
    };

    // 使用特定建议
    const useSuggestion = (content: string) => {
      if (content) {
        replyContent.value = content;
      }
    };

    // 发送回复
    const sendReply = async () => {
      if (!replyContent.value.trim()) return;
      
      try {
        // 设置编辑器内容
        await setEditorContent2(replyContent.value);
        
        // 点击发送按钮
        const sendButton = document.querySelector('button[aria-label="发送"]');
        if (sendButton) {
          (sendButton as HTMLButtonElement).click();
          // 关闭提醒窗口
          closeAlert();
        }
      } catch (error) {
        console.error('发送消息时出错:', error);
      }
    };

    // 关闭提醒并标记为已读
    const closeAlert = async () => {
      try {
        // 获取认证信息
        const authInfo = await getAuthInfo();
        
        // 发送已读标记到后台
        if (props.chatId) {
          const response = await fetch('https://tools.kikimami.com/crm/api/markaireplayasread/', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'authorization': authInfo.authorization,
              'ptoken': authInfo.ptoken
            },
            body: JSON.stringify({
              chat_serialized: props.chatId
            })
          });

          const result = await response.json();
          if (!result.success) {
            console.error('标记已读失败:', result.message);
          }
        }
      } catch (error) {
        console.error('标记已读时发生错误:', error);
      } finally {
        emit('close');
      }
    };

    return {
      showSuggestions,
      replyContent,
      toggleSuggestions,
      useSuggestion,
      sendReply,
      closeAlert
    };
  }
});
</script>

<style scoped>
.ai-reply-alert {
  position: fixed;
  top: 95px;
  left: 50%;
  transform: translateX(-50%);
  background: #fff3cd;
  padding: 20px;
  border-radius: 8px;
  border: 1px solid #ffeeba;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  z-index: 9999;
  min-width: 300px;
  max-width: 600px;
  max-height: 80vh;
  overflow-y: auto;
  user-select: text;
  cursor: auto;
}

.ai-reply-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.ai-reply-header h4 {
  margin: 0;
  color: #856404;
}

.ai-reply-content p {
  margin: 0 0 15px 0;
}

.reply-input-container {
  background: #fff;
  padding: 10px;
  border-radius: 4px;
  border: 1px solid #ddd;
  margin-bottom: 15px;
}

#replyContent {
  width: 100%;
  min-height: 100px;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-bottom: 10px;
  resize: vertical;
  font-family: inherit;
}

.reply-actions {
  display: flex;
  justify-content: flex-end;
}

.ai-reply-suggestions {
  border-top: 1px solid #ffeeba;
  padding-top: 15px;
  margin-top: 15px;
}

.ai-reply-suggestions h4 {
  margin: 0 0 15px 0;
  color: #856404;
}

.suggestions-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.suggestion-item {
  background: rgba(255,255,255,0.7);
  padding: 12px;
  border-radius: 6px;
}

.suggestion-purpose {
  color: #0a58ca;
  font-weight: 600;
  margin-bottom: 8px;
}

.suggestion-content, .suggestion-proof {
  margin-bottom: 8px;
}

.suggestion-proof {
  color: #6c757d;
  font-size: 0.9em;
}

.ai-reply-footer {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
  margin-top: 20px;
}

button {
  cursor: pointer;
}

.close-btn {
  padding: 6px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: white;
}

.send-btn, .view-btn, .use-suggestion-btn {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  background: #00a884;
  color: white;
}

.use-suggestion-btn {
  margin-top: 8px;
}
</style> 